/*
* 这个图形报表与通用报表多了两个柱形图
* 所以大多数逻辑都与通用报表一样
* 参考：containers/data-center/report/travel-report/travel-report.js
* */

import React from "react";
import { Icon, message, Spin, Popover, Button } from 'antd';
import FeeDetailReportService
  from "containers/data-center/report/travel-report/fee-detail-report/fee-detail-report.service";
import 'styles/data-center/report/travel-report/fee-detail-report/fee-detail-report.scss';
import Charts from 'components/echarts';
import SearchArea from 'components/search-area';
import { deepFullCopy, messages } from "share/common";
import menuRoute from 'routes/menuRoute';
import TRService from 'containers/data-center/report/travel-report/travel-report.service';
import { connect } from "react-redux";
import ReportTypeWithVendor
  from 'containers/data-center/report/travel-report/components/report-type-with-vendor/report-type-with-vendor';
import ResizeTable from "components/resize-table";
import PersonDetail from 'containers/data-center/report/travel-report/fee-detail-report/components/person-detail';
import FeeDetail from 'containers/data-center/report/travel-report/fee-detail-report/components/fee-detail';
import FDRDEService
  from 'containers/data-center/report/travel-report/fee-detail-report/fee-detail-report-data-engine.service';
import ExportModal from "components/template/export-modal/export-modal";

class FeeDetailReport extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      chartsHeight: 400,
      optionFee: FDRDEService.optionExample,
      optionPerson: FDRDEService.optionExample,
      showSearchArea: true,
      cardData: {},
      loading: true,
      loadingSearchArea: true,
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      searchFormExtraFieldsArr: [],
      //额外的搜索参数，依赖，主要用来控制依赖的参数是否显示与可用等
      extraFieldsSearchParams: {
        setOfBooksId: null,
        payee_type: null
      },
      //搜索区：特殊字段，额外添加
      extraFieldsSearchArea: [],
      //特殊字段，选择之后的值
      extraFieldsValues: {
        // 注意选择之后的值，对应的key是 cost ，但是上传的时候不一定是 cost，
        // 可能是 cc1,需要在查询的时候去根据后端字段改变
        cost: undefined,
        expense_type: undefined,
        cost_center_code: undefined
      },
      reportDetail: {},
      //搜索区字段：根据后端定
      searchForm: [],
      //搜索传参：根据后端定
      params: {},
      //列名：根据后端定
      columns: [],
      //报表数据
      data: [],
    }
  }

  componentDidMount() {
    TRService.InitSearchComponents(this.props.language.code)
      .then((res) => {
        this.getReportDetail(this.props.params.id);
      })
  }

  //获取表详细结构
  getReportDetail(id, noSearch, callback) {
    TRService.getReportDetail(id)
      .then((res) => {
        this.setState({
          reportDetail: res.data,
          searchForm: res.data.searchFormByMan,
          params: res.data.paramsByMan,
          columns: res.data.setColumnByMan,
          loadingSearchArea: false
        }, () => {
          //自动触发搜索账套改变时间，设置依赖项的初始值
          let val = TRService.getBooksDefaultValueById("books", this.state.searchForm);
          this.eventSearchAreaHandle('books', val, "man");
          this.setExtraFieldsByRes(this.state.reportDetail, () => {
            let params = TRService.setDefaultTime(this.state.searchForm);
            if (!noSearch) {
              this.handleSearch(params);
            }
            if (callback) {
              callback();
            }
          });
        })
      })
  }

  /*
    * 通过后端的code，设置是否显示额外的搜索组件
    * 有依赖的搜索组件，设置好，进入回调
    * */
  setExtraFieldsByRes = (reportDetail, callback) => {
    //有依赖项
    if (reportDetail.extraFieldsSearchArea.length > 0) {
      //可能显示字段（这些字段都会有依赖）
      let searchFormExtraFieldsArrMaybe = [
        {
          id: '',//根据后端赋值，这是写默认的会重新覆盖
          backend_id: "report_type_add_vendor",//
          label: "",//根据后端赋值，这是写默认的会重新覆盖
          getField: (
            <ReportTypeWithVendor
              multiple={true}
              title={messages('data-center.key127')/*报销类型*/}
              setOfBooksId={this.state.extraFieldsSearchParams.setOfBooksId}
              onCancel={this.onConfirmReportTypeWithVendor}
              onConfirm={this.onConfirmReportTypeWithVendor}
            />
          )
        },
      ];
      //通过后端返回的依赖字段，去 searchFormExtraFieldsArrMaybe 数组里面找到对应的字段
      let searchFormExtraFieldsArr = [];
      let reportDetail = this.state.reportDetail;
      reportDetail.extraFieldsSearchArea.map(item => {
        let field = TRService.findRightDependecyField(item, searchFormExtraFieldsArrMaybe);
        field.id = item.criteriaPropName;
        field.label = item.criteriaName;
        field.seqNo = item.criteriaSeqNo;
        searchFormExtraFieldsArr.push(field);
      });
      this.setState({
        searchFormExtraFieldsArr,
        //额外的扩展字段
        extraFieldsSearchArea: searchFormExtraFieldsArr.map(item => {
          return {
            filed: item.getField,
            seqNo: item.seqNo
          }
        }),
      }, () => {
        callback && callback();
      })
    } else {
      callback && callback();
    }
  }
  //设置额外搜索组件值
  onEventHandlerByType = (val, tyle) => {
    let { extraFieldsValues } = this.state;
    extraFieldsValues[tyle] = val;
    this.setState({
      extraFieldsValues
    })
  };
  //报销单状态
  onConfirmReportTypeWithVendor = (val) => {
    this.onEventHandlerByType(val, 'report_type_add_vendor')
  };
  getAnalysisReport = () => {
    this.setState({ loading: true });
    let { params, pagination, columns, searchFormExtraFieldsArr, extraFieldsValues } = this.state;
    if (searchFormExtraFieldsArr.length > 0) {
      searchFormExtraFieldsArr.map(item => {
        if (item.backend_id === "company") {
          params[item.id] = extraFieldsValues.company;
        }
        if (item.backend_id === "report_type_add_vendor") {
          params[item.id] = extraFieldsValues.report_type_add_vendor;
        }
      })
    }
    let request = {
      id: this.props.params.id,
      page: this.state.pagination.page,
      size: this.state.pagination.pageSize,
      criteria: params
    };
    //更新子组件两个图形报表
    this.childFeeDetailExpense.refreshComponentLoading();
    this.childFeeDetailExpense.refreshComponent(request);
    this.childPersonDetailExpense.refreshComponentLoading();
    this.childPersonDetailExpense.refreshComponent(request);
    //
    FeeDetailReportService.getAllDataBySearchParams(request)
      .then(resList => {
        /*
        * 这个函数封装了三个接口
        * 这个返回三个接口的数据，第一个是底部的table，与通用报表处理方式不一样；
        * 还有有两个图形报表特殊
        * 只有人为点击搜索的时候会多走两个接口，之后用户翻页，就是只请求单独接口
        * */
        let [res, optionFeeRes, optionPersonRes] = resList;
        pagination.total = Number(res.headers['x-total-count']) ? Number(res.headers['x-total-count']) : 0;
        let optionFee = FDRDEService.feeExpenseReport(optionFeeRes.data);
        let optionPerson = FDRDEService.personExpenseReport(optionPersonRes.data);
        this.setState({
          optionFee,
          optionPerson,
          columns,
          data: res.data,
          loading: false,
          pagination
        })
      })
      .catch(() => {
        this.setState({
          loading: false,
        })
      })
  }
  //当搜索自动发送改变
  eventSearchAreaHandle = (e, item, type) => {
    let { extraFieldsSearchParams, extraFieldsValues } = this.state;
    if (e === "books") {
      if (type !== 'man') {
        message.warn(messages('data-center.key129')/*请重选依赖账套的搜索条件*/)
      }
      Object.assign(extraFieldsValues, {
        expense_type: undefined,
        cost: undefined,
        cost_center_code: undefined,
      });
      extraFieldsSearchParams.setOfBooksId = null;
      if (item.length > 0 && item[0].setOfBooksId) {
        extraFieldsSearchParams.setOfBooksId = item[0].setOfBooksId;
      }
      this.setState({
        extraFieldsValues,
        extraFieldsSearchParams
      }, () => {
        this.setExtraFieldsByRes(this.state.reportDetail);
      })
    }
  }
  //检测是否有这个参数
  _checkHasParam = (searchForm, type) => {
    let len = searchForm.length;
    for (let i = 0; i < len; i++) {
      let item = searchForm[i];
      if (item.backend_id === type) {
        return true;
      }
    }
    return false;
  }
  //清空搜索
  clearSearchHandle = () => {
    let { extraFieldsSearchParams, extraFieldsValues, params, searchForm } = this.state;
    extraFieldsValues.expense_type = undefined;
    Object.assign(extraFieldsSearchParams, {
      setOfBooksId: undefined,
      company: undefined,
    });
    for (let key in params) {
      params[key] = "";
    }
    params = TRService.setDefaultTime(searchForm);
    let val = TRService.getBooksDefaultValueById("books", searchForm);
    if (val.length > 0 && val[0].setOfBooksId) {
      extraFieldsSearchParams.setOfBooksId = val[0].setOfBooksId;
      if (this._checkHasParam(searchForm, 'books')) {
        params['set_of_books_id'] = val[0].setOfBooksId;
      }
    }
    if (this._checkHasParam(searchForm, 'year')) {
      params['YEAR'] = (new Date()).getFullYear();
    }
    this.setState({
      extraFieldsSearchParams,
      params,
    }, () => {
      this.setExtraFieldsByRes(this.state.reportDetail, () => {
        this.handleSearch(this.state.params);
      });
    })
  };
  //点击搜搜索
  handleSearch = (values) => {
    if ((!values.set_of_books_id || values.set_of_books_id.length === 0) &&
      !this.state.params['set_of_books_id']) {
      message.warn(messages('data-center.key136')/*账套不能为空*/);
      return;
    }
    let dateFields = TRService.getNeedCheckFields(values);
    //这种时间类型只需检查开始不能大于开始
    let dateFieldsSlave = TRService.getNeedCheckFieldsSlave(values);
    if (TRService.checkDateValueIsNull(dateFields, values)) {
      message.warn(messages('data-center.key16'/*请选择时间*/));
      return;
    }
    if (TRService.checkDateValueStartEnd(dateFields, values) || TRService.checkDateValueStartEndSlave(dateFieldsSlave, values)) {
      message.warn(messages('data-center.key17'/*开始时间须小于结束时间*/));
      return;
    }
    if (TRService.checkDateValueGap(dateFields, values)) {
      message.warn(messages('data-center.key91')/*查询时间跨度不能超过12个月*/);
      return;
    }
    let needArrParam = {};
    for (let key in values) {
      let item = values[key];
      if (item && item.constructor && item.constructor.name === "Array") {
        /*
        * 支持多选
        * task 25884
        * 每一行代表一个选择器，多个参数
        * */
        let supportMultipleArr = [
          'reimb_status',//报销单状态
          'inv_check_result', 'check_result',//发票检验结果  发票检验结果返回码  两个查询参数对应一个搜索器
          'receipt_type_no',//发票类型
          'company_oid', 'applicant_company_oid',//公司
          'department_code', 'applicant_dept_code',//部门
          'receipt_label_types',//发票标签
          'applicant_oid', 'rejecter_oid', 'approver_oid',//申请人
          'report_type_add_vendor', 'form_oid',//带供应商的报销类型code
          'report_status_add_vendor', 'status',//带供应商的报销状态code
        ];
        if (supportMultipleArr.indexOf(key) > -1) {
          needArrParam[key] = JSON.stringify(values[key]);
        } else {
          //目前不支持传数组，所以下面取第一个
          values[key] = item[0]
        }
      }
    }
    let { pagination, searchForm } = this.state;
    pagination.page = 0;
    pagination.current = 1;
    //这个地方用deepCopy，只是因为在子组件要监听nextProps变化
    let v = deepFullCopy(values);
    let _params = TRService.transDateToArr(v, searchForm, TRService.getNeedCheckFields(v), TRService.getNeedCheckFieldsSlave(v));
    let _paramsT = TRService.tansYearMonth(_params, this.state.searchForm);
    let paramsT = Object.assign(_paramsT, needArrParam);
    this.setState({
      pagination,
      params: Object.assign(this.state.params, paramsT)
    }, () => {
      this.getAnalysisReport()
    })
  };

  //返回到列表
  handleBack = () => {
    let path = menuRoute.getRouteItem('report', 'key').url;
    this.context.router.push(path);
  };

  showSearchAreaHandler = () => {
    this.setState({
      showSearchArea: true
    })
  };
  hideSearchAreaHandler = () => {
    this.setState({
      showSearchArea: false
    })
  };

  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        current: pagination.current,
        page: pagination.current - 1,
        pageSize: pagination.pageSize,
        total: pagination.total
      }
    }, () => {
      this.getUserFeeDetailReport();
    })
  };

  //获取 累计超标明细表
  getUserFeeDetailReport = () => {
    this.setState({ loading: true });
    let { params, pagination, columns, searchFormExtraFieldsArr, extraFieldsValues } = this.state;
    //需要写函数去匹配：目前只考虑成本中心
    if (searchFormExtraFieldsArr.length > 0) {
      searchFormExtraFieldsArr.map(item => {
        if (item.backend_id === "company") {
          params[item.id] = extraFieldsValues.company;
        }
        if (item.backend_id === "report_type_add_vendor") {
          params[item.id] = extraFieldsValues.report_type_add_vendor;
        }
        if (item.backend_id === "expense_type") {
          params[item.id] = extraFieldsValues.expense_type;
        }
      })
    }
    let request = {
      id: this.props.params.id,
      page: this.state.pagination.page,
      size: this.state.pagination.pageSize,
      criteria: params
    };
    FeeDetailReportService.getUserFeeDetailReport(request)
      .then(res => {
        pagination.total = Number(res.headers['x-total-count']) ? Number(res.headers['x-total-count']) : 0;
        this.setState({
          columns,
          data: res.data,
          loading: false,
          pagination
        })
      })
  }
  onMountFeeDetailExpense = (feeDetailExpense) => {
    this.childFeeDetailExpense = feeDetailExpense;
  }
  onMountPersonDetailExpense = (personDetailExpense) => {
    this.childPersonDetailExpense = personDetailExpense;
  }

  renderReportTable() {
    let { pagination, data, columns, loading, loadingSearchArea } = this.state;
    if (loadingSearchArea) {
      return (
        <div className="loading-container">
          <Spin tip={messages('data-center.key20'/*正在初始化报表列*/)}
                size="large"/>
        </div>
      )
    } else {
      return (
        <ResizeTable
          scroll={{ x: columns.length * 200 }}
          dataSource={data}
          loading={loading}
          pagination={pagination}
          onChange={this.onChangePager}
          columns={columns}
          size="middle"
          bordered/>
      )
    }
  }

  renderSearchArea() {
    let { extraFieldsSearchArea, searchForm, loadingSearchArea, loading } = this.state;
    if (loadingSearchArea) {
      return (
        <div className="loading-container">
          <Spin tip={messages('data-center.key19'/*正在初始化查询参数*/)}
                size="large"/>
        </div>
      )
    } else {
      return (
        <SearchArea
          eventHandle={this.eventSearchAreaHandle}
          sorted={true}
          extraFieldsSorted={extraFieldsSearchArea}
          searchForm={searchForm}
          clearHandle={this.clearSearchHandle}
          submitHandle={this.handleSearch}
          loading={loading}/>
      )
    }
  }

  //设置表结构
  goToSetting = () => {
    let path = menuRoute.getRouteItem('travel-report-setting', 'key').url.replace(':id', this.props.params.id);
    this.context.router.push(path);
  }

  render() {
    const {
      showSearchArea,
      chartsHeight,
      optionFee,
      optionPerson, loadingSearchArea, params, data, reportDetail
    } = this.state;
    let request = {
      id: this.props.params.id,
      page: this.state.pagination.page,
      size: this.state.pagination.pageSize,
      criteria: params
    }
    let className = showSearchArea ? 'show-sa' : "hidden-sa";
    return (
      <div className="fee-detail-report-wrap">
        <div className='s-wrap'>
          <div className='search-area-btn-wrap'>
            {!showSearchArea && <div className="show-search-area-btn-top" onClick={this.showSearchAreaHandler}>
              <Popover content={messages('data-center.key114')/*展开收起搜索区*/}><Icon
                type="caret-down"/></Popover>
            </div>}
          </div>
          <div className={className}>
            {this.renderSearchArea()}
          </div>
          <div className='search-area-btn-wrap'>
            {showSearchArea && <div className="show-search-area-btn" onClick={this.hideSearchAreaHandler}>
              <Popover content={messages('data-center.key115')/*收起搜索区*/}><Icon
                type="caret-up"/></Popover>
            </div>}
          </div>
        </div>
        <div className='fee-detail-wrap'>

          <div className='inner-fee-detail-wrap'>
            <div className='chart-wrap-title'>{messages('data-center.key137')/*累计超标统计图*/}</div>
            <div className='chart-wrap-one'>
              <div className='chart-one'>
                <Charts options={optionFee}
                        height={chartsHeight}
                        width="100%"
                        className="echarts-item"/>
              </div>
              <div className='inner-table-wrap'>
                <div className="echarts-item-title-wrap echarts-item-user-detail">
                  <FeeDetail onRef={this.onMountFeeDetailExpense}/>
                </div>
              </div>
              <div className='clear'/>
            </div>
            <div className='chart-line'/>
            <div className='chart-wrap-one'>
              <div className='chart-one'>
                <Charts options={optionPerson}
                        height={chartsHeight}
                        width="100%"
                        className="echarts-item"/>
              </div>
              <div className='inner-table-wrap'>
                <div className="echarts-item-title-wrap echarts-item-user-detail">
                  <PersonDetail onRef={this.onMountPersonDetailExpense}/>
                </div>
              </div>
              <div className='clear'/>
            </div>
          </div>
          <div className='table-wrap'>
            <div className='chart-wrap-title'>
              <span>{messages('data-center.key138')/*累计超标明细表*/}</span>
              <div className='f_right'>
                <Button onClick={this.goToSetting}>
                  {messages('data-center.key22'/*字段设置*/)}
                </Button>&nbsp;&nbsp;
                <ExportModal
                  style={{ display: "inline-block" }}
                  codeCheck={true}
                  disabled={data.length < 1 || loadingSearchArea}
                  type={"btn"}
                  btnType={"primary"}
                  exportTitle={messages('data-center.key21'/*导出数据*/)}
                  exportType="REPORT"
                  exportCondition={{
                    "exportType": "REPORT",
                    "reportSearchDTO": request,
                    "command": reportDetail.reportCode
                  }}
                />
              </div>
            </div>
            <div className='inner-table-wrap'>
              {this.renderReportTable()}
            </div>
          </div>
        </div>

        <div>
          <a className='back-a' onClick={this.handleBack}>
            <Icon className='back-a-icon' type="rollback"/>
            {messages('common.back')}
          </a>
        </div>
      </div>
    )
  }
}

FeeDetailReport.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization,
    company: state.login.company,
    language: state.main.language,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(FeeDetailReport);

